# 展示格子
import math

import pygame
import sys

from pygame_test.MoveRect import MoveRect


def show_cells():
    pygame.init()
    winx = 200
    winy = 200
    screen = pygame.display.set_mode((winx, winy))
    fps = 20
    fclock = pygame.time.Clock()
    r = pygame.Rect(0, 0, 20, 33)
    # rs = full_cells_by_rect(screen.get_rect(), r)
    rs = full_cells_by_nums(screen.get_rect(), 10, 6)
    color = (255, 255, 0)
    mrs = []
    for r in rs:
        mrs.append(MoveRect(r.x, r.y, r.w, r.h, color, 0))
    pos=-1,-1
    # print(rs)
    while True:
        screen.fill((0, 0, 0))
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif e.type == pygame.MOUSEBUTTONDOWN:
                print('mouse button down', e.pos[0], e.pos[1])
                pos = e.pos[0], e.pos[1]
            # elif e.type == pygame.MOUSEBUTTONUP:
                # print('mouse button up', e.pos[0], e.pos[1])
        # pos = 100,100
        for i, one in enumerate(mrs):
            # pygame.draw.rect(screen,(255,255,0),one,2)
            # print(pos)
            if one.is_inside(pos[0],pos[1]):
                one.is_clicked = True
            else:
                # print('out')
                one.is_clicked = False
        for one in mrs:
            if one.is_clicked:
                one.color = (255, 0, 0)
            else:
                one.color = (0, 255, 255)
            one.draw(screen)

        pygame.display.update()


def full_cells_by_rect(rect_big, rect_small):
    # 根据给定的大rect和小rect,将小rect铺满大rect,返回小rect列表
    row = math.ceil(rect_big.h / rect_small.h)
    column = math.ceil(rect_big.w / rect_small.w)
    print(f'row: {row}, collumn:{column}')
    rects = []
    for i in range(column):
        for j in range(row):
            x = rect_big.x + i * rect_small.w
            y = rect_big.y + j * rect_small.h
            w = rect_small.w
            h = rect_small.h
            rects.append(pygame.Rect(x, y, w, h))
    return rects


def full_cells_by_nums(rect_big, num_x, num_y):
    # 根据给定x方向和y方向的个数, 将rect_big铺满, 返回rect列表
    w = rect_big.w / num_x
    h = rect_big.h / num_y
    print(w, h)
    rect_small = pygame.Rect(0, 0, w, h)
    return full_cells_by_rect(rect_big, rect_small)


if __name__ == '__main__':
    show_cells()
    # rs = count_cells(pygame.Rect(0,0,221,101),pygame.Rect(0,0,22,22))
    # print(len(rs))
    # print(rs)
